package site.fantasycube.demo.util;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * 描述：http请求工具类
 *
 * @author huan&yue
 * @since 2022/4/27 17:38
 */
public class HttpUtil {


    /**
     * get请求工具
     *
     * @param url        请求地址
     * @param nameValuePairList    请求参数集合（new BasicNameValuePair("P", "1")）
     * @param headerList 请求头集合（new BasicHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36")）
     * @return 返回结果体字符串
     */
    public static String getHttp(String url, List<NameValuePair> nameValuePairList, List<Header> headerList) {

        try {
            //构造请求路径，并添加参数
            URI uri = new URIBuilder(url).addParameters(nameValuePairList).build();
            //创建CloseableHttpClient对象（忽略证书的重点）
            CloseableHttpClient httpClient = null;
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            //构造HttpClient
            httpClient = HttpClients.custom().setSSLSocketFactory(scsf).setDefaultHeaders(headerList).build();
            //构造HttpGet请求
            HttpUriRequest httpUriRequest = RequestBuilder.get().setUri(uri).build();
            //获取结果
            HttpResponse httpResponse = httpClient.execute(httpUriRequest);
            //获取返回结果中的实体
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * get请求工具
     *
     * @param url        请求地址
     * @param nameValuePairList    请求参数集合（new BasicNameValuePair("P", "1")）
     * @param headerList 请求头集合（new BasicHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36")）
     * @return 返回结果体字符串
     */
    public static InputStream getHttpToInput(String url, List<NameValuePair> nameValuePairList, List<Header> headerList) {

        try {
            //构造请求路径，并添加参数
            URI uri = new URIBuilder(url).addParameters(nameValuePairList).build();
            //创建CloseableHttpClient对象（忽略证书的重点）
            CloseableHttpClient httpClient = null;
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            //构造HttpClient
            httpClient = HttpClients.custom().setSSLSocketFactory(scsf).setDefaultHeaders(headerList).build();
            //构造HttpGet请求
            HttpUriRequest httpUriRequest = RequestBuilder.get().setUri(uri).build();
            //获取结果
            HttpResponse httpResponse = httpClient.execute(httpUriRequest);
            //获取返回结果中的实体
            HttpEntity entity = httpResponse.getEntity();
            return entity.getContent();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
